package com.boxin.ims.modules.wechat.web.front;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.boxin.framework.base.dao.DaoHelper;
import com.boxin.framework.base.utils.Constants;
import com.boxin.framework.base.utils.DateUtils;
import com.boxin.ims.modules.bi.dao.BIDao;
import com.boxin.ims.modules.html.utils.RegexUtil;
import com.boxin.ims.modules.momarketing.common.QRCodeUtils;
import com.boxin.ims.modules.momarketing.entity.CustomPage;
import com.boxin.ims.modules.momarketing.entity.QRCode;
import com.boxin.ims.modules.momarketing.service.CouponConfigService;
import com.boxin.ims.modules.momarketing.service.CustomPageService;
import com.boxin.ims.modules.momarketing.service.QRCodeService;
import com.boxin.ims.modules.recharge.service.RechargeService;
import com.boxin.ims.modules.wechat.busi.BusinessProcessor;
import com.boxin.ims.modules.wechat.busi.DefaultProcessor;
import com.boxin.ims.modules.wechat.busi.ExchangeProcessor;
import com.boxin.ims.modules.wechat.busi.LinktoProcessor;
import com.boxin.ims.modules.wechat.busi.LocationProcessor;
import com.boxin.ims.modules.wechat.busi.LotteryProcessor;
import com.boxin.ims.modules.wechat.busi.MemberBindProcessor;
import com.boxin.ims.modules.wechat.busi.SceneLotteryProcessor;
import com.boxin.ims.modules.wechat.busi.SeckillQueryProcessor;
import com.boxin.ims.modules.wechat.busi.WeatherProcessor;
import com.boxin.ims.modules.wechat.busi.game.AnswerRaceProcessor;
import com.boxin.ims.modules.wechat.busi.game.NumberProcessor;
import com.boxin.ims.modules.wechat.entity.BusinessNewsReply;
import com.boxin.ims.modules.wechat.entity.EventMessage;
import com.boxin.ims.modules.wechat.entity.ImageMessage;
import com.boxin.ims.modules.wechat.entity.LangType;
import com.boxin.ims.modules.wechat.entity.LocationMessage;
import com.boxin.ims.modules.wechat.entity.LotteryRecord;
import com.boxin.ims.modules.wechat.entity.MemberScore;
import com.boxin.ims.modules.wechat.entity.MusicMessage;
import com.boxin.ims.modules.wechat.entity.NewsReply;
import com.boxin.ims.modules.wechat.entity.RecommendConfig;
import com.boxin.ims.modules.wechat.entity.SeckillConfig;
import com.boxin.ims.modules.wechat.entity.TextMessage;
import com.boxin.ims.modules.wechat.entity.UserBusiness;
import com.boxin.ims.modules.wechat.entity.UserDefine;
import com.boxin.ims.modules.wechat.entity.VoiceMessage;
import com.boxin.ims.modules.wechat.entity.WeChat;
import com.boxin.ims.modules.wechat.entity.WechatConfig;
import com.boxin.ims.modules.wechat.entity.WechatMember;
import com.boxin.ims.modules.wechat.entity.WechatMenu;
import com.boxin.ims.modules.wechat.entity.WechatMessage;
import com.boxin.ims.modules.wechat.entity.WechatScene;
import com.boxin.ims.modules.wechat.entity.WechatSceneFans;
import com.boxin.ims.modules.wechat.entity.WechatWelcome;
import com.boxin.ims.modules.wechat.entity.tmessage.BusinessMessageTemplate;
import com.boxin.ims.modules.wechat.entity.tmessage.UserMessageTemplate;
import com.boxin.ims.modules.wechat.score.entity.ExchangeRecord;
import com.boxin.ims.modules.wechat.score.service.ExchangeRecordService;
import com.boxin.ims.modules.wechat.score.service.ScoreExchangeService;
import com.boxin.ims.modules.wechat.service.BusinessNewsReplyService;
import com.boxin.ims.modules.wechat.service.LotteryConfigService;
import com.boxin.ims.modules.wechat.service.LotteryRecordService;
import com.boxin.ims.modules.wechat.service.LotteryScopeService;
import com.boxin.ims.modules.wechat.service.MemberScoreService;
import com.boxin.ims.modules.wechat.service.NewsReplyService;
import com.boxin.ims.modules.wechat.service.RecommendConfigService;
import com.boxin.ims.modules.wechat.service.RegionService;
import com.boxin.ims.modules.wechat.service.SeckillConfigService;
import com.boxin.ims.modules.wechat.service.UserDefineService;
import com.boxin.ims.modules.wechat.service.WeChatService;
import com.boxin.ims.modules.wechat.service.WechatConfigService;
import com.boxin.ims.modules.wechat.service.WechatDaoHelper;
import com.boxin.ims.modules.wechat.service.WechatMemberService;
import com.boxin.ims.modules.wechat.service.WechatMenuService;
import com.boxin.ims.modules.wechat.service.WechatMessageService;
import com.boxin.ims.modules.wechat.service.WechatMybatisService;
import com.boxin.ims.modules.wechat.service.WechatSceneFansService;
import com.boxin.ims.modules.wechat.service.WechatSceneService;
import com.boxin.ims.modules.wechat.service.WechatWelcomeService;
import com.boxin.ims.modules.wechat.service.tmessage.UserMessageTemplateService;
import com.boxin.ims.modules.wechat.tmessage.TemplateMessage;
import com.boxin.ims.modules.wechat.tmessage.TemplateMessageFactory;
import com.boxin.ims.modules.wechat.utils.AssertUtils;
import com.boxin.ims.modules.wechat.utils.DataUtils;
import com.boxin.ims.modules.wechat.utils.MessageProcessorUtils;
import com.boxin.ims.modules.wechat.utils.ScoreUtils;
import com.boxin.ims.modules.wechat.utils.SessionUtils;
import com.boxin.ims.modules.wechat.utils.SpringUtils;
import com.boxin.ims.modules.wechat.utils.TemplateMessageUtils;
import com.boxin.ims.modules.wechat.utils.TokenUtils;
import com.boxin.ims.modules.wechat.utils.WechatInterfaceUtils;
import com.boxin.ims.modules.wechat.utils.WechatMenuUtils;
import com.boxin.ims.modules.wechat.utils.WechatUtils;
import com.boxin.ims.modules.wechat.utils.XMLUtils;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.utils.FileUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.zhixun.mobile.modules.member.service.MemberService;

@Controller
@RequestMapping(value = Global.MOBILE_SITE_PATH + "/wp")
public class WeChatPlatformController  extends BaseController{
	private final static Logger logger = Logger.getLogger(WeChatPlatformController.class);
	
	@Autowired
	WeChatService weChatService;
	
	@Autowired
	UserMessageTemplateService userMessageTemplateService;
	
	@Autowired
	RegionService regionService;
	
	@Autowired
	SystemService systemService;
	
	@Autowired
	WechatConfigService wechatConfigService;
	
	@Autowired
	WechatWelcomeService  wechatWelcomeService;
	
	@Autowired
	NewsReplyService newsReplyService;
	
	@Autowired
	DaoHelper daoHelper;
	
	
	@Autowired
	LotteryRecordService lotteryRecordService;
	
	@Autowired
	WechatMybatisService wechatMybatisService;
	
	@Autowired
	WechatMemberService wechatMemberService;
	
	@Autowired
	MemberScoreService memberScoreService;
	
	@Autowired
	CouponConfigService couponConfigService;
	
	@Autowired
	LotteryScopeService lotteryScopeService;
	
	@Autowired
	LotteryConfigService lotteryConfigService;
	
	@Autowired
	ScoreExchangeService scoreExchangeService;
	
	
	@Autowired 
	LotteryProcessor lotteryProcessor;
	
	
	@Autowired
	NumberProcessor numberProcessor;
	
	@Autowired
	AnswerRaceProcessor answerRaceProcessor;
	
	
	

	@Autowired
	ExchangeProcessor exchangeProcessor;
	
	@Autowired
	WeatherProcessor weatherProcessor;
	
	@Autowired
	DefaultProcessor defaultProcessor;
	
	@Autowired
	WechatDaoHelper wechatDaoHelper;
	
	
	@Autowired
	SceneLotteryProcessor sceneLotteryProcessor;
	
	@Autowired
	UserDefineService userDefineService;
	
	@Autowired
	LinktoProcessor linktoProcessor;
	
	
	
	@Autowired
	MemberBindProcessor memberBindProcessor;
	
	@Autowired
	SeckillQueryProcessor seckillQueryProcessor;
	
	
	@Autowired
	SeckillConfigService seckillConfigService;
	
	
	@Autowired
	LocationProcessor locationProcessor;
	
	@Autowired
	QRCodeService qrCodeService;
	
	@Autowired
	RechargeService rechargeService;
	
	@Autowired
	BIDao biDao;
	
	@Autowired
	WechatMessageService wechatMessageService;
	
	@Autowired
	BusinessNewsReplyService businessNewsReplyService;
	
	@Autowired
	private CustomPageService customPageService;
	
	@Autowired
	private MemberService memberService;
	
	@Autowired
	private WechatSceneService	wechatSceneService;
	
	@Autowired
	RecommendConfigService recommendConfigService;
	
	@Autowired
	private WechatSceneFansService wechatSceneFansService;
	
	@Autowired
	private WechatMenuService wechatMenuService;
	
	@Autowired
	private ExchangeRecordService exchangeRecordService;
	

	
	@RequestMapping(value = {"chat", ""})
	public void chat(HttpServletRequest request, HttpServletResponse response, Model model) {
		try {
			
			//logger.debug("进入微信消息处理.....");
			String method = request.getMethod();
			if("GET".equals(method)){
				valid(request,response,model);
				return;
			}
			
			//logger.debug("验证通过....");
			
			String wid	 =  request.getParameter("wid");		//后台设置ID WeChat 的ID
			WeChat weChat = weChatService.get(Long.parseLong(wid));
			String reply = weChat.getRemarks();	//默认回复内容
			User user = weChat.getUser();	//微信平台所属用户
			UserDefine userDefine = userDefineService.getByUserId(user.getId());
			
			//1.获取自己所有服务列表
			
			
			//logger.debug("进入消息处理环节.......");
			
			StringBuffer sb = new StringBuffer();
			BufferedReader bReader =   request.getReader();
			String line = "";
			while((line = bReader.readLine()) != null){
				sb.append(line);
			}
			
			logger.debug("接收到的请求内容是："+sb.toString());
			
			
			Map<String,String> map = XMLUtils.xml2Map(sb.toString());
			
			
//			loggerMessage(user, map,request);		//记录交互数据
			
			
			
			TextMessage textMessage = new TextMessage(map);
			TextMessage processorMessage = new TextMessage(map);		//供Processor使用
			
			//上行数据
			String upcon = textMessage.getContent();	//用户输入的内容
			String openId = textMessage.getToUserName();	//用户 Open Id
			String wechatId = textMessage.getFromUserName();	//微信公众平台Id
			if(com.thinkgem.jeesite.common.utils.StringUtils.isEmpty(weChat.getWpId())){
				weChat.setWpId(wechatId);
				weChatService.save(weChat);
			}else{
				if(!weChat.getWpId().equals(wechatId)){
					reply = "你好.";
					//返回给微信用户的信息
					try {
						textMessage.setContent(reply);
						response.getWriter().print(textMessage.replyMessage() );
						logger.info(textMessage.replyMessage());
					} catch (Exception e) {
						e.printStackTrace();
					}		
					return ;
				}
			}
			
			textMessage.setContent(reply);	//默认自动回复的内容
			reply = textMessage.replyMessage();
			
			System.err.println(SessionUtils.getLastUpContent(openId));
		
//			if(upcon.equals("开挂模式")){
//				SessionUtils.addSession(openId, "开挂模式");		//创建会话
//				
//				textMessage.setContent("您已经进入开挂模式，发送退出退出该模式");
//				response.getWriter().print(textMessage.replyMessage() );
//			}
//			
//			if(upcon.equals("退出")){
////				SessionUtils.removeSession(openId);
//				textMessage.setContent("退出开挂模式");
//				response.getWriter().print(textMessage.replyMessage() );
//			}
//			
//			if("开挂模式".equals(SessionUtils.getLastUpContent(openId))){
//				return ;
//			}
			
			//判断事件,回复欢迎词
			String MsgType = map.get("xml.MsgType");
			
			if(EventMessage.MSG_TYPE.equals(MsgType)){		//事件类型的处理 ： 
				Boolean flag = false;
				WechatMember regMember = wechatMemberService.getByUserIdAndOpenId(user.getId(), openId);
				if( regMember ==null ){
					flag=true;
					//第一次关注 
					final WechatMember  wechatMember = 	addWechatMember(user, openId, weChat, request);
					regMember = wechatMember;
				}else {
				}
				if(EventMessage.EVENT_TYPE_JOIN.equals(map.get("xml.Event"))){	//订阅事件
					
					
					
					
					WechatScene  scene=null;
					//渠道二维码处理
					logger.debug("添加渠道二维码...");
					if(map.get("xml.EventKey") != null  &&  map.get("xml.EventKey").startsWith("qrscene_")){
						try {
							WechatSceneFans fans = new WechatSceneFans();
							fans.setDay(DateUtils.getTodayString());
							fans.setOpenId(openId);
							fans.setUser(user);
							String sceneId = map.get("xml.EventKey").substring(8,map.get("xml.EventKey").length());
							//scene = 	wechatSceneService.wechatSceneBySceneId(user.getId(),sceneId);
							String ticket = map.get("xml.Ticket");
							scene = 	wechatSceneService.wechatSceneByTicket(user.getId(),sceneId,ticket);
							
							if(scene!=null){
								fans.setSceneId(scene.getId());
								fans.setName(scene.getScene());
							}
							fans.setType("关注");
							fans.setStatus(WechatScene.STATUS_NORMAL);
							wechatSceneFansService.save(fans);
							
							//处理器
							if(StringUtils.isNotEmpty(scene.getProcessorId())){
								
								BusinessProcessor bProcessor = (BusinessProcessor)SpringUtils.getBean(scene.getProcessorId());
								if(bProcessor!=null){
									///
									bProcessor.setUser(user);
									bProcessor.setWeChat(weChat);
									bProcessor.setOpenId(openId);
									bProcessor.setRequest(request);
									bProcessor.setResponse(response);
									bProcessor.setMessageMap(map);
									bProcessor.setTextMessage(processorMessage);
									Map<String,Object> varMap = bProcessor.getVarMap();
									varMap.put("groupId", scene.getBindId());	//绑写的数据源ID,这里指的是 群组ID
									varMap.put("paramMapJson", scene.getParamMapJson());	//绑写的数据源ID,这里指的是 群组ID
									varMap.put("flag", flag);
									varMap.put("sceneId",sceneId);
									bProcessor.setVarMap(varMap);
									bProcessor.process();
								}
							}
							
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					
					
					if(scene!=null){
						if(StringUtils.isNotEmpty(scene.getKeyword())){
							//将关键字回复放置到textmessage类中
							TextMessage message = new TextMessage();
							message.setContent(scene.getKeyword());
							
							defaultProcessor.setRequest(request);
							defaultProcessor.setUser(user);
							defaultProcessor.setWeChat(weChat);
							defaultProcessor.setOpenId(openId);
							defaultProcessor.setResponse(response);
							defaultProcessor.setMessageMap(map);
							defaultProcessor.setTextMessage(message);
							defaultProcessor.process();
							
							
							return ;
						}
					}
					
					
					logger.debug("欢迎消息处理...");
					WechatWelcome wechatWelcome = weChat.getWechatWelcome();
					if(wechatWelcome!=null){
						
						// //选择默认的欢迎回复内容
						if (MusicMessage.MSG_TYPE.equals(wechatWelcome.getType())) {
							MusicMessage musicMessage = new MusicMessage(map);
							musicMessage.setMusicUrl(wechatWelcome.getMusicUrl());
							musicMessage.setHQMusicUrl(wechatWelcome.getMusicUrl());
							musicMessage.setTitle(wechatWelcome.getTitle());
							musicMessage.setDescription(wechatWelcome
									.getDescription());
							response.getWriter().print(musicMessage.replyMessage());
							logger.debug("回复的图文内容:" + musicMessage.replyMessage());
							return;
							
						} else if (ImageMessage.MSG_TYPE_NEWS.equals(wechatWelcome
								.getType())) { // 回复图文信息
							ImageMessage imageMessage = new ImageMessage(map);
							imageMessage.setArticleCount("1");
							imageMessage.setTitle(wechatWelcome.getTitle());
							imageMessage.setDescription(wechatWelcome
									.getDescription());
							imageMessage.setPicUrl(wechatWelcome.getPicUrl());
							imageMessage.setUrl(wechatWelcome.getUrl());
							
							Map<String, String> params = Maps.newHashMap();
							params.put("welcomeId", wechatWelcome.getId() + "");
							List<NewsReply> newsReplyList = wechatMybatisService
									.findNewsReply(params);
							
							replaceUrlParameters(newsReplyList, user, openId); // 处理动态的URL参数
							
							response.getWriter().print(
									imageMessage.replyMessage(newsReplyList));
							logger.debug("回复的图文内容:" + imageMessage.replyMessage());
							return;
							
						} else {
							
							
							textMessage.setContent(wechatWelcome.getContent());
							response.getWriter().print(textMessage.replyMessage());
							printReplyLogger(textMessage.replyMessage());
							 final  String openId_=openId;
							 final  WechatMember regMember_=regMember;
							  new Thread( new Runnable() {
		                            @Override
		                            public void run() {
		                                try {
		                                    Thread.sleep(1000);    //延迟1秒
		                                  //发送客服
		        							String title="【免费家庭清洁】过年清洁不用愁，慧司蒙家庭清洁免费送！";
		        							String PicUrl="http://hsm.hbweiyinqing.cn/huisimeng/userfiles/huisimeng/admin_huisi_1483070145238.jpg";
		        							String Description="临近春节，您还在为节日前后的家庭清扫而烦吗？获得免费的保洁服务赶紧来参加吧";
		        							String Url="http://mp.weixin.qq.com/s/WQxUItQufHbHxzDGJ_rqjA";
		        							String Count="";
		        								ImageMessage imageMessage=new ImageMessage();
		        								imageMessage.setPicUrl(PicUrl);
		        								imageMessage.setTitle(title);
		        								imageMessage.setDescription(Description);
		        								imageMessage.setUrl(Url);
		        								imageMessage.setArticleCount(Count);
		        								List<ImageMessage> list =new ArrayList<ImageMessage>();
		        								list.add(imageMessage);
		        								String content = WechatInterfaceUtils.newsListMessageParams(openId_,list);
//		        								WechatInterfaceUtils.sendTextMessageToMember(2l, regMember_, content); 
		                                } catch (Exception e) {

		                                }
		                            }
		                        }).start();
							
								
							return;
						}
						
					}else{
						logger.debug("欢迎消息为空，不需要回复!");
					}

				} else if(EventMessage.EVENT_TYPE_SCAN.equals(map.get("xml.Event"))){
					
					//渠道二维码处理
					logger.debug("添加渠道二维码...已关注过，本次是扫描");
					if(map.get("xml.EventKey") != null ){
						try {
							WechatSceneFans fans = new WechatSceneFans();
							fans.setDay(DateUtils.getTodayString());
							fans.setOpenId(openId);
							fans.setUser(user);
							String sceneId = map.get("xml.EventKey").replaceAll("qrscene_", "").trim();
							WechatScene  scene = 	wechatSceneService.wechatSceneBySceneId(user.getId(),sceneId);
							if(scene!=null){
								fans.setSceneId(scene.getId());
								fans.setName(scene.getScene());
							}
							fans.setType("扫描");
							fans.setStatus(WechatScene.STATUS_NORMAL);
							wechatSceneFansService.save(fans);
							
							
							
							//处理器
							if(StringUtils.isNotEmpty(scene.getProcessorId())){
									BusinessProcessor bProcessor = (BusinessProcessor)SpringUtils.getBean(scene.getProcessorId());
									if(bProcessor!=null){
										///
										bProcessor.setUser(user);
										bProcessor.setWeChat(weChat);
										bProcessor.setOpenId(openId);
										bProcessor.setRequest(request);
										bProcessor.setResponse(response);
										bProcessor.setMessageMap(map);
										bProcessor.setTextMessage(processorMessage);
										Map<String,Object> varMap = bProcessor.getVarMap();
										varMap.put("groupId", scene.getBindId());	//绑写的数据源ID,这里指的是 群组ID
										varMap.put("paramMapJson", scene.getParamMapJson());	//绑写的数据源ID,这里指的是 群组ID
										varMap.put("flag", flag);	
										varMap.put("sceneId",sceneId);
										bProcessor.setVarMap(varMap);
										bProcessor.process();
										
										return ;
									}
							}
							
							if(scene!=null){
								if(StringUtils.isNotEmpty(scene.getKeyword())){
									
									//将关键字回复放置到textmessage类中
									TextMessage message = new TextMessage();
									message.setContent(scene.getKeyword());
									
									
									defaultProcessor.setRequest(request);
									defaultProcessor.setUser(user);
									defaultProcessor.setWeChat(weChat);
									defaultProcessor.setOpenId(openId);
									defaultProcessor.setResponse(response);
									defaultProcessor.setMessageMap(map);
									defaultProcessor.setTextMessage(message);
									defaultProcessor.process();
								}
							}
							
							return ;
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					
					
					
					
					
					
					
					
					WechatWelcome wechatWelcome = weChat.getWechatWelcome();
					if(wechatWelcome!=null){
						
						//选择默认的欢迎回复内容
						if(MusicMessage.MSG_TYPE.equals(wechatWelcome.getType())){
							MusicMessage musicMessage = new MusicMessage(map);
							musicMessage.setMusicUrl(wechatWelcome.getMusicUrl() );
							musicMessage.setHQMusicUrl(wechatWelcome.getMusicUrl());
							musicMessage.setTitle(wechatWelcome.getTitle());
							musicMessage.setDescription(wechatWelcome.getDescription());
							response.getWriter().print(musicMessage.replyMessage() );
							logger.debug("回复的图文内容:"+musicMessage.replyMessage());
							return ;
							
						}else if(ImageMessage.MSG_TYPE_NEWS.equals(wechatWelcome.getType())){	//回复图文信息
							ImageMessage imageMessage = new ImageMessage(map);
							imageMessage.setArticleCount("1");
							imageMessage.setTitle(wechatWelcome.getTitle());
							imageMessage.setDescription(wechatWelcome.getDescription());
							imageMessage.setPicUrl(wechatWelcome.getPicUrl());
							imageMessage.setUrl(wechatWelcome.getUrl());
							
							
							Map<String,String> params = Maps.newHashMap();
							params.put("welcomeId", wechatWelcome.getId()+"");
							List<NewsReply> newsReplyList = wechatMybatisService.findNewsReply(params);
							
							replaceUrlParameters(newsReplyList, user, openId);	//处理动态的URL参数
							
							response.getWriter().print(imageMessage.replyMessage(newsReplyList));
							logger.debug("回复的图文内容:"+imageMessage.replyMessage());
							return ;
							
						}else{
							String content = wechatWelcome.getContent();
							String newContent = replaceContentParameters(content, user, openId);
							textMessage.setContent(newContent);
							response.getWriter().print(textMessage.replyMessage() );
							printReplyLogger(textMessage.replyMessage() );
							return;
						}
					}
					
				}else if(EventMessage.EVENT_TYPE_QUIT.equals(map.get("xml.Event"))){//退订事件
					//删除会员积分，取消会员申请关系
					WechatMember member =	wechatMemberService.getByWechatMemberId(weChat.getUser(), openId);
					if(member != null){
						member.setScore(0);
						member.setActiveScore(0);
						member.setConsumeScore(0);
						member.setCreditScore(0);
						member.setUnusable(0);
						wechatMemberService.save(member);
						ScoreUtils.addWechatCancelScore(member,member.getScore());
					}
					
					//不再删除会员这条记录，只是将其的积分置为0
					//wechatMemberService.deleteByUserIdAndWechatId(weChat.getUser().getId(),openId) ;
					return ;
				}else if(EventMessage.EVENT_CLICK.equals(map.get("xml.Event"))){	//菜单事件---点击事件
					WechatMessage message = new WechatMessage();
					String eventKey = map.get("xml.EventKey");
//					WechatMenu wechatMenu = wechatMenuService.getByKey(eventKey);
//					upcon=wechatMenu.getKeywords();
					if(WechatMenuUtils.BIND_MEMBER_KEY.equals(eventKey)){	//绑定会员的事件
						upcon = "会员申请";
						loggerMessageByClick(user, map, upcon);
					}else if((WechatMenuUtils.SIGN_MEMBER_KEY.equals(eventKey))){	//签到的事件
						upcon = "签到";
						loggerMessageByClick(user, map, upcon);
					}else if((WechatMenuUtils.LOTTERY_KEY.equals(eventKey))){	//抽奖
						upcon = "抽奖";
						loggerMessageByClick(user, map, upcon);
					}else if(WechatMenuUtils.SCORE_EXCHANGE_KEY.equals(eventKey)){	//积分兑换
						upcon = "积分兑换";
						loggerMessageByClick(user, map, upcon);
					}else if(WechatMenuUtils.SCORE_QUERY_KEY.equals(eventKey)){
						upcon = "积分";
						loggerMessageByClick(user, map, upcon);
					}else{
						WechatMenu menu = 	WechatMenuUtils.getWechatMenuByEventKey(eventKey);
						if(menu != null){
							upcon = menu.getKeywords();
							processorMessage.setContent(upcon);
							logger.debug("菜单Key="+menu.getEventKey()+",关键词:"+menu.getKeywords());
							loggerMessageByClick(user, map, upcon);
							if(StringUtils.isEmpty(upcon)){
								reply = weChat.getRemarks();
								TextMessage txtMsg = new TextMessage(map);
								txtMsg.setContent(reply);
								response.getWriter().print(txtMsg.replyMessage() );
								printReplyLogger(txtMsg.replyMessage());
								return ;
							}
						}else {
							loggerMessageByClick(user, map, null);
							reply = weChat.getRemarks();
							TextMessage txtMsg = new TextMessage(map);
							txtMsg.setContent(reply);
							response.getWriter().print(txtMsg.replyMessage() );
							printReplyLogger(txtMsg.replyMessage());
							return ;
						}
					}
					
				}else if(EventMessage.EVENT_VIEW.equals(map.get("xml.Event"))){		//查看 导航 网址
					String url = map.get("xml.EventKey");
					System.out.println("要访问的URL:"+url);
					url = url +((url.contains("?") ? "&" : "?"))+"openid="+openId;
					return ;
				}else if(EventMessage.EVENT_SCANCODE_WAIT.equals(map.get("xml.Event"))){		//二维码扫描待待事件
					EventMessage eventMessage = new EventMessage(map);
					
					String result = eventMessage.getScanResult();
					
					String replys="";
					if(regMember!=null && "1".equals(regMember.getIsAdmin())){
						//核销
						QRCode qRCode = qrCodeService.getBySN(result);
						if(qRCode==null){
							replys="无效二维码！";
						}else{
							
							ExchangeRecord exchangeRecord = exchangeRecordService.findByQrCode(qRCode.getId());
							if(exchangeRecord!=null && "1".equals(exchangeRecord.getStatus())){
								replys="不可重复核销！";
							}else{
								replys="核销成功!";
								exchangeRecordService.updateStatusByQrCode(qRCode.getId(),"1");
							}
						}
						
						
					}else{
						replys="您没有权限!";
					}
					String content = WechatInterfaceUtils.textMessageParams(regMember.getWechatId(),replys);
					WechatInterfaceUtils.sendTextMessageToMember(2l, regMember, content); 
					/*TextMessage txtMsg = new TextMessage(map);
					txtMsg.setContent(replys);
					response.getWriter().print(txtMsg.replyMessage() );*/
					return ;
					
				}else if(EventMessage.EVENT_SCANCODE_PUSH.equals(map.get("xml.Event"))){		//二维码扫描结果事件
					EventMessage eventMessage = new EventMessage(map);
					String scanResult = eventMessage.getScanResult();
					
					logger.debug("扫描结果:"+scanResult);
					return ;
					
				}else if(EventMessage.EVENT_PIC_SYSPHTOTO.equals(map.get("xml.Event"))){		//系统拍照
					
					
					
				}else if(EventMessage.EVENT_PIC_WEIXIN.equals(map.get("xml.Event"))){			//微信相册
					
					
					
				}else if(EventMessage.EVENT_PIC_PHOTO_ALBUM.equals(map.get("xml.Event"))){		//系统相册
					
					
					
				} else{
					return ;
				}
				
			}else if(ImageMessage.MSG_TYPE.equals(MsgType)){//微圈分享转发有奖活 
				
				return;
				
			}else if(LocationMessage.MSG_TYPE.equals(MsgType)){	//位置 消息处理
				
//				locationProcessor.setUser(user);
//				locationProcessor.setWeChat(weChat);
//				locationProcessor.setOpenId(openId);
//				locationProcessor.setRequest(request);
//				locationProcessor.setResponse(response);
//				locationProcessor.setMessageMap(map);
//				LocationMessage locationMessage = new LocationMessage(map);
//				locationProcessor.setLocationMessage(locationMessage);
//				locationProcessor.process();
				
				reply ="位置服务还未开放，敬请期待...";
				
				defaultProcessor.setRequest(request);
				defaultProcessor.setUser(user);
				defaultProcessor.setWeChat(weChat);
				defaultProcessor.setOpenId(openId);
				defaultProcessor.setRequest(request);
				defaultProcessor.setResponse(response);
				defaultProcessor.setMessageMap(map);
				defaultProcessor.setTextMessage(processorMessage);
				defaultProcessor.writeToUser(reply);
				return ;
				
				
			} else if (VoiceMessage.MSG_TYPE.equals(MsgType)){		//语音识别
				
				
				
				
				if(user.getInterfaceFlag() ){//是否开通了高级接口
					
					VoiceMessage vMessage = new VoiceMessage(map);
					upcon = WechatUtils.getKeyWord(vMessage.getRecognition())  ;
					logger.debug("语音识别内容:"+upcon);
					if(StringUtils.isEmpty(upcon)){
						reply ="很抱歉，语音未能识别...";
						defaultProcessor.setRequest(request);
						defaultProcessor.setUser(user);
						defaultProcessor.setWeChat(weChat);
						defaultProcessor.setOpenId(openId);
						defaultProcessor.setRequest(request);
						defaultProcessor.setResponse(response);
						defaultProcessor.setMessageMap(map);
						defaultProcessor.setTextMessage(processorMessage);
						defaultProcessor.writeToUser(reply);
						return ;
						
					}else{
						map.put("xml.Content", upcon);
						processorMessage.setContent(upcon);
					}
				}else{
					reply ="很抱歉，我们暂时还没有开放语音识别功能...";
					defaultProcessor.setRequest(request);
					defaultProcessor.setUser(user);
					defaultProcessor.setWeChat(weChat);
					defaultProcessor.setOpenId(openId);
					defaultProcessor.setRequest(request);
					defaultProcessor.setResponse(response);
					defaultProcessor.setMessageMap(map);
					defaultProcessor.setTextMessage(processorMessage);
					defaultProcessor.writeToUser(reply);
					return ;
				}
			}
			
			/////////////////////////纯文本内容的处理//////////////////////////////
			
			if(430000008 == user.getId()){	//金农用
				//正则处理
				//1。纯英文字母
				boolean isChar  = RegexUtil.isCharString(upcon);
				if(isChar){
					answerRaceProcessor.setUser(user);
					answerRaceProcessor.setWeChat(weChat);
					answerRaceProcessor.setOpenId(openId);
					answerRaceProcessor.setRequest(request);
					answerRaceProcessor.setResponse(response);
					answerRaceProcessor.setMessageMap(map);
					answerRaceProcessor.setTextMessage(processorMessage);
					answerRaceProcessor.process();
					
					return ;
				}
				
				
				//2.纯数字
				boolean isNumber  = RegexUtil.isNumber(upcon);
				if(isNumber){
					
					numberProcessor.setUser(user);
					numberProcessor.setWeChat(weChat);
					numberProcessor.setOpenId(openId);
					numberProcessor.setRequest(request);
					numberProcessor.setResponse(response);
					numberProcessor.setMessageMap(map);
					numberProcessor.setTextMessage(processorMessage);
					numberProcessor.process();
					
					return ;
				}
			}
			
			
			
			
		if(upcon!=null){
			if(upcon.equals("秒杀")){
				
				linktoProcessor.setUser(user);
				linktoProcessor.setWeChat(weChat);
				linktoProcessor.setOpenId(openId);
				linktoProcessor.setRequest(request);
				linktoProcessor.setResponse(response);
				linktoProcessor.setMessageMap(map);
				linktoProcessor.setTextMessage(processorMessage);
				
				linktoProcessor.setTitle("超值秒杀等你拿");
				linktoProcessor.setDesc("点击图片进入超值秒杀,祝您好运!");
				String seckillPic = "seckill.jpg";
				
				String picUrl = "http://weixin.zhaotang.net/zt/userfiles/seckill/"+seckillPic+"?t="+System.currentTimeMillis();
				String url = "http://weixin.zhaotang.net/zt/f/member/seckills?uid="+user.getId() +"&wechatId="+openId+"&topage=seckill";
				
				SeckillConfig seckillConfig =	seckillConfigService.getByUserId(user.getId()) ;
				if(seckillConfig!=null){
					
					//图片文件
					if( com.thinkgem.jeesite.common.utils.StringUtils.isNotEmpty(seckillConfig.getSeckillPic())){
						seckillPic = seckillConfig.getSeckillPic();
						picUrl = "http://weixin.zhaotang.net/zt/userfiles/seckill/"+seckillPic+"?t="+System.currentTimeMillis();
					}
					
					
					//是否多图文回复
					List<BusinessNewsReply>  businessNewsList =  businessNewsReplyService.findByTypeSourceId(BusinessNewsReply.MSG_TYPE_SECKILL, user.getId(), user.getId()+"");
					if(businessNewsList != null && !businessNewsList.isEmpty()){	//多图文回复
						
						BusinessNewsReply bnr = new BusinessNewsReply();
						bnr.setDescription(seckillConfig.getSeckillDesc());
						bnr.setTitle(seckillConfig.getSeckillTitle());
						bnr.setPicUrl(picUrl);
						bnr.setUrl(url);
						businessNewsList.add(0, bnr);
						
						List<NewsReply> newsReplies = DataUtils.convertToNewsReplyList(businessNewsList);
						
						linktoProcessor.writeMultiImagesToUser(newsReplies);
						return ;
					}
					
					
				} 
				
				linktoProcessor.setPicUrl(picUrl);
				linktoProcessor.setUrl(url );
				
				linktoProcessor.process();
				
			}else if(upcon.startsWith("微会员")){
				
				memberBindProcessor.setUser(user);
				memberBindProcessor.setWeChat(weChat);
				memberBindProcessor.setOpenId(openId);
				memberBindProcessor.setRequest(request);
				memberBindProcessor.setResponse(response);
				memberBindProcessor.setMessageMap(map);
				memberBindProcessor.setTextMessage(processorMessage);
				memberBindProcessor.process();
				return ;
				
			}else if("会员申请".equals(upcon) ){
				
				linktoProcessor.setUser(user);
				linktoProcessor.setWeChat(weChat);
				linktoProcessor.setOpenId(openId);
				linktoProcessor.setRequest(request);
				linktoProcessor.setResponse(response);
				linktoProcessor.setMessageMap(map);
				linktoProcessor.setTextMessage(processorMessage);
				String title = "微会员申请";
				if(userDefine != null && StringUtils.isNotEmpty(userDefine.getRegMemberTitle())){
					title = userDefine.getRegMemberTitle();
				}
				String desc = "点击图片进入微会员申请页面，成 为我们的会员后，您将可以参与各种优惠活动以及享受更高级的服务,谢谢!";
				if(userDefine != null && StringUtils.isNotEmpty(userDefine.getRegMemberDesc())){
					desc = userDefine.getRegMemberDesc();
				}
				
				linktoProcessor.setTitle(title);
				linktoProcessor.setDesc(desc);
				String picName = "reg.jpg";
				if(userDefine!=null && StringUtils.isNotEmpty(userDefine.getRegMemberPic())){
					picName = userDefine.getRegMemberPic();
				}
				
				String picUrl ="http://weixin.zhaotang.net/zt/userfiles/images/"+picName+"?t="+System.currentTimeMillis();
				String url = "http://weixin.zhaotang.net/zt/f/member/bind?uid="+user.getId() +"&wechatId="+openId;
				//是否多图文回复
				if(userDefine!=null){
					List<BusinessNewsReply>  businessNewsList =  businessNewsReplyService.findByTypeSourceId(BusinessNewsReply.MSG_TYPE_MEMBER,user.getId(), user.getId()+"");
					if(businessNewsList != null && !businessNewsList.isEmpty()){	//多图文回复
						
						BusinessNewsReply bnr = new BusinessNewsReply();
						bnr.setDescription(desc);
						bnr.setTitle(title);
						bnr.setPicUrl(picUrl);
						bnr.setUrl(url);
						businessNewsList.add(0, bnr);
						
						List<NewsReply> newsReplies = DataUtils.convertToNewsReplyList(businessNewsList);
						linktoProcessor.writeMultiImagesToUser(newsReplies);
						return ;
					}
				}
				
				
				linktoProcessor.setPicUrl(picUrl);
				linktoProcessor.setUrl( url);
				linktoProcessor.process();
				
				return;
			}else if(upcon.contains("登录")){
				
				linktoProcessor.setUser(user);
				linktoProcessor.setWeChat(weChat);
				linktoProcessor.setOpenId(openId);
				linktoProcessor.setRequest(request);
				linktoProcessor.setResponse(response);
				linktoProcessor.setMessageMap(map);
				linktoProcessor.setTextMessage(processorMessage);
				
				linktoProcessor.setTitle("微会登录");
				linktoProcessor.setDesc("");
				linktoProcessor.setPicUrl("http://weixin.zhaotang.net/zt/userfiles/images/reg.jpg?t="+System.currentTimeMillis());
				linktoProcessor.setUrl( "http://weixin.zhaotang.net/zt/f/member/login?uid="+user.getId() +"&wechatId="+openId);
				
				linktoProcessor.process();
				
				return ;
				
			}else if(upcon.equals("留言板")){
				
				linktoProcessor.setUser(user);
				linktoProcessor.setWeChat(weChat);
				linktoProcessor.setOpenId(openId);
				linktoProcessor.setRequest(request);
				linktoProcessor.setResponse(response);
				linktoProcessor.setMessageMap(map);
				linktoProcessor.setTextMessage(processorMessage);
				String title = "留言板";
				
				
				if(userDefine != null && StringUtils.isNotEmpty(userDefine.getGuestBookTitle())){
					title = userDefine.getGuestBookTitle();
				}
				
				String desc = "点击图片进入微留言板页面，将您的建议和建议提给我们，以便我们更好的提供服务质量，谢谢!";
				if(userDefine != null && StringUtils.isNotEmpty(userDefine.getGuestBookDesc())){
					desc = userDefine.getGuestBookDesc();
				}
				
				linktoProcessor.setTitle(title);
				linktoProcessor.setDesc(desc);
				String picName = "guestbook.jpg";
				if(userDefine!=null && StringUtils.isNotEmpty(userDefine.getGuestBookPic())){
					picName = userDefine.getGuestBookPic();
				}
				
				linktoProcessor.setPicUrl("http://weixin.zhaotang.net/zt/userfiles/images/"+picName+"?t="+System.currentTimeMillis());
				linktoProcessor.setUrl( "http://weixin.zhaotang.net/zt/f/mom/guestBook/me?uid="+user.getId() +"&oid="+openId);
				
				linktoProcessor.process();
				
				return ;
				
			}else if(upcon.equals("网页签到")){
				
				linktoProcessor.setUser(user);
				linktoProcessor.setWeChat(weChat);
				linktoProcessor.setOpenId(openId);
				linktoProcessor.setRequest(request);
				linktoProcessor.setResponse(response);
				linktoProcessor.setMessageMap(map);
				linktoProcessor.setTextMessage(processorMessage);
				String title = "签到送积分";
				
				
				if(userDefine != null && StringUtils.isNotEmpty(userDefine.getSignupTitle())){
					title = userDefine.getSignupTitle();
				}
				
				String desc = "点击图片进入签到送积分页面。";
				if(userDefine != null && StringUtils.isNotEmpty(userDefine.getSignupDesc())){
					desc = userDefine.getSignupDesc();
				}
				
				linktoProcessor.setTitle(title);
				linktoProcessor.setDesc(desc);
				String picName = "signupscore.jpg";
				if(userDefine!=null && StringUtils.isNotEmpty(userDefine.getSignupPic())){
					picName = userDefine.getSignupPic();
				}
				
				
				UserBusiness userBusiness = 	WechatUtils.getUserBusinessByKeyWords(user.getId(),"签到");
				String picUrl = "http://weixin.zhaotang.net/zt/userfiles/images/"+picName+"?t="+System.currentTimeMillis();
				String url = "http://weixin.zhaotang.net/zt/f/member/tosignup?uid="+user.getId() +"&oid="+openId;
				linktoProcessor.setPicUrl(picUrl);
				linktoProcessor.setUrl( url);
				
				
				if(userDefine!=null){
					List<BusinessNewsReply>	businessNewsList = businessNewsReplyService.findByTypeSourceId("business", user.getId() , userBusiness.getId()+"");
					if(businessNewsList != null && !businessNewsList.isEmpty()){	//多图文回复
						/**
						 * 多图文回复
						 */	
						BusinessNewsReply bnr = new BusinessNewsReply();
						bnr.setDescription(desc);
						bnr.setTitle(title);
						bnr.setPicUrl(picUrl);
						bnr.setUrl(url);
						businessNewsList.add(0, bnr);
						
						List<NewsReply> newsReplies = DataUtils.convertToNewsReplyList(businessNewsList);
						if(newsReplies!=null  && !newsReplies.isEmpty()){
							for(NewsReply newsReply : newsReplies){
								String descTemp = newsReply.getDescription();
								descTemp = descTemp.replaceAll("%分值%", userDefine.getSignScore()+"");
								newsReply.setDescription(descTemp);
							}
							
						}
						
						linktoProcessor.writeMultiImagesToUser(newsReplies);
						return ;
					}
				}
				
				
				linktoProcessor.process();
				
				return ;
				
			}else if(upcon.equals("广告积分") || upcon.equals("广告签到")){
				
				List<CustomPage>  pageList = 	null;//customPageService.findAllByUserId(user.getId());
				if(upcon.equals("广告积分")){
					 pageList = 	customPageService.findAdvertPagesByUserId(user.getId());
				}else{
					 pageList = 	customPageService.findSignupPageByUserId(user.getId());
				}
				if(pageList != null && !pageList.isEmpty()){
					Random rand = new Random();
					int  n  = 0;
					int limit = 0;
					while(true){
						
						try {
							n  = rand.nextInt(pageList.size());
						} catch (Exception e) {
							n=0;
							break;
						}
						if(n>=0 && n <= pageList.size()-1){
							break;
						}
						
						
						if(limit>=15){	//
							n=0;
							break;
						}
						limit ++;
					}
					
					CustomPage page = pageList.get(n);
					
					linktoProcessor.setUser(user);
					linktoProcessor.setWeChat(weChat);
					linktoProcessor.setOpenId(openId);
					linktoProcessor.setRequest(request);
					linktoProcessor.setResponse(response);
					linktoProcessor.setMessageMap(map);
					linktoProcessor.setTextMessage(processorMessage);
					String url = "http://weixin.zhaotang.net/zt/userfiles/pages/"+page.getPicname();
					String siteUrl = "http://weixin.zhaotang.net/zt/f/site/toRichpage/"+page.getId()+"?uid="+user.getId()+"&wechatId="+openId;
					
					linktoProcessor.writeImageToUser(page.getName(), "", url, siteUrl);
					return ;
				}
				
			  
			}else{//未找到以上固定的关键词，则用用户自定义的
				//服务性的数据处理
				BusinessProcessor processor =	MessageProcessorUtils.getBusinessProcessorByKeywords(weChat, processorMessage, map, request, response);
				if(processor!=null){
					processor.process();
					return;
				}else{
					defaultProcessor.setRequest(request);
					defaultProcessor.setUser(user);
					defaultProcessor.setWeChat(weChat);
					defaultProcessor.setOpenId(openId);
					defaultProcessor.setResponse(response);
					defaultProcessor.setMessageMap(map);
					defaultProcessor.setTextMessage(processorMessage);
					defaultProcessor.process();
				}
				
				
				return  ;
			}
		}	
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-6-26  上午10:26:00
	 * @function <p> 回复内容 </p>
	 * @param content
	 */
	private void printReplyLogger(String content){
		logger.debug("回复的全内容是:"+content);
	}
	
	@RequestMapping(value = "valid")
	public void valid(HttpServletRequest request, HttpServletResponse response, Model model){
		
		System.out.println("微信请认证消息.....");
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = 	   request.getParameter("nonce");
		String wid		 =  request.getParameter("wid");		//后台设置ID WeChat 的ID
		String echostr = request.getParameter("echostr");
		String Token = "";
		
		if(!StringUtils.isBlank(wid)){  //从平台中获取Token 进行绑定
			try {
				WeChat weChat  = weChatService.get(Long.parseLong(wid));
				if(weChat!=null){
					Token  = weChat.getToken();
				}
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("查找ID为:"+wid+"的用户Token失败!");
			}
		}
		
		try {
			
			String[] ArrTmp = { Token, timestamp, nonce };
			Arrays.sort(ArrTmp);
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < ArrTmp.length; i++) {
				sb.append(ArrTmp[i]);
			}
			
			String pwd = Encrypt(sb.toString());
			logger.debug("pwd=="+pwd);
			logger.debug("signature=="+signature);
			logger.debug("echostr=="+echostr);
			
			if(pwd.equals(signature)){
				if(!"".equals(echostr) && echostr != null){
					response.getWriter().write(echostr);
					logger.debug("绑定成功...");
				}else{
					response.getWriter().write("非法签名,认证失败!");
					logger.debug("绑定失败...非法签名,认证失败!");
				}
			}else{
				response.getWriter().write("非法签名,认证失败!");
				logger.debug("非法签名,认证失败!");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-6-21  上午10:09:30
	 * @function <p> 图片或声音的资源文件 URL </p>
	 * @param request
	 * @param response
	 * @return
	 */
	
	@RequestMapping(value =  "vr")
	public String viewResource(HttpServletRequest request, HttpServletResponse response){
		
		String rid = request.getParameter("rid");
		String fileName = request.getParameter("fname");
		String vtype = request.getParameter("vtype");	//访问类型   reply和welcome
		
		String wid = request.getParameter("wid");		// 
		WechatConfig config = null;
		if(com.thinkgem.jeesite.common.utils.StringUtils.isNotEmpty(wid)){
			config = wechatConfigService.get(Long.parseLong(wid));
		}
		String filepath = "";
		String type = ImageMessage.MSG_TYPE_NEWS;
		
		if(com.thinkgem.jeesite.common.utils.StringUtils.isEmpty(vtype)  ||  "reply".equals(vtype)){	//多图文时 查NewsReply表中的资源
			NewsReply newsReply = 	newsReplyService.get(Long.parseLong(rid));
			filepath = newsReply.getFilePath();
		}else{
			if(config != null){
				WechatWelcome welcome =  config.getWeChat().getWechatWelcome();
				type = welcome.getType();
				filepath = welcome.getFilePath();
			}
		}
		
		logger.debug("访问要下载的图片文件位置是为 filepath :"+filepath);
		
		if(MusicMessage.MSG_TYPE.equals(type)){	//音乐
			try {
				//1.回复的声音文件
				 File file = new File(filepath);
				 OutputStream outputStream = response.getOutputStream();
				 InputStream inputStream = new FileInputStream(file);
				 
				 response.setContentType("audio/mp3");
				 
				 byte[] buffer = new byte[1024];
				 int i = -1;
				 while ((i = inputStream.read(buffer)) != -1) {
				  outputStream.write(buffer, 0, i);
				 }
				 outputStream.flush();
				 outputStream.close();
				 inputStream.close();
				 outputStream = null;
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			
		}else if(ImageMessage.MSG_TYPE_NEWS.equals(type)){
			try {
				
				//2.回复的图文
				File file = new File(filepath);
//				BufferedImage image = 	ImageIO.read(file);
				
				OutputStream outputStream = response.getOutputStream();
//				ImageIO.write(image, "JPEG", out);
//				
//				out.flush();
//				out.close();
				 String contentType = "image/jpeg";
				 if(filepath.toLowerCase().endsWith("gif")){
					 contentType = "image/gif";
				 }
				 response.setContentLength((int)file.length());
				 response.setContentType(contentType+";charset=UTF-8"); 
				 InputStream inputStream = new FileInputStream(file);
				 byte[] buffer = new byte[1024];
				 int i = -1;
				 while ((i = inputStream.read(buffer)) != -1) {
				  outputStream.write(buffer, 0, i);
				 }
				 outputStream.flush();
				 outputStream.close();
				 inputStream.close();
				 outputStream = null;
				
				 
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		
		
		return null;
	}
	
	
	public String Encrypt(String strSrc) {
		MessageDigest md = null;
		String strDes = null;

		byte[] bt = strSrc.getBytes();
		try {
			md = MessageDigest.getInstance("SHA-1");
			md.update(bt);
			strDes = bytes2Hex(md.digest()); //to HexString
		} catch (NoSuchAlgorithmException e) {
			System.out.println("Invalid algorithm.");
			return null;
		}
		return strDes;
	}

	public String bytes2Hex(byte[] bts) {
		String des = "";
		String tmp = null;
		for (int i = 0; i < bts.length; i++) {
			tmp = (Integer.toHexString(bts[i] & 0xFF));
			if (tmp.length() == 1) {
				des += "0";
			}
			des += tmp;
		}
		return des;
	}
	
	public boolean isChinese(String str){  
	     boolean result=false;  
	     for (int i = 0; i < str.length(); i++){  
	          int chr1 = (char) str.charAt(i);  
	          if(chr1>=19968&&chr1<=171941){//汉字范围 \u4e00-\u9fa5 (中文)  
	              result = true;  
	          } 
	     }  
	     return result;  
	} 
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-9-8  下午11:26:44
	 * @function <p> 添加微信至会员 </p>
	 * @param user
	 * @param wechatId
	 */
	public WechatMember addWechatMember(User user,String wechatId,WeChat weChat,HttpServletRequest request){
		System.out.println("jin ru ================"+user.getId()+"jin ru ================"+wechatId);
		WechatMember wechatMember = wechatMemberService.getByWechatMemberId(user, wechatId);
		if(wechatMember == null){	//不存在则添加
			
			wechatMember = new WechatMember();
			wechatMember.setUser(user);
			wechatMember.setWechatId(wechatId);
			wechatMember.setScore(0);
			wechatMember.setActiveScore(0);
			wechatMember.setConsumeScore(0);
			wechatMember.setCreditScore(0);
			wechatMember.setMoney(0);
			wechatMember.setLastSignTime(null);
			wechatMember.setIsRandomPassword(false);
			wechatMember.setSex("保密");
			wechatMember.setRecommendScore(0);
			
			String accessToken = TokenUtils.getAPIToken(weChat);
			Boolean advanceInterface = memberService.selectInterfaceFlagByuserID(user.getId());	//是否开通了高级接口
			try {
				if(advanceInterface){
					WechatMember temp = WechatInterfaceUtils.getUserMessage(accessToken,wechatMember.getWechatId(),	LangType.zh_CN);
					if(temp!=null){
						if(temp.getNickname()==null){
							temp.setNickname("匿名");
						}
						wechatMember.setNickname(temp.getNickname());
						wechatMember.setName(temp.getNickname());
						wechatMember.setAge(temp.getAge());
						wechatMember.setHeadimgurl(temp.getHeadimgurl());
						wechatMember.setCity(temp.getCity());
						wechatMember.setCountry(temp.getCountry());
						String sex = temp.getSex();
						if("1".equals(sex)){
							wechatMember.setSex("男");
						}
						if("2".equals(sex)){
							wechatMember.setSex("女");
						}
						if("0".equals(sex)){
							wechatMember.setSex("保密");
						}
						wechatMember.setProvince(temp.getProvince());
					}
					
				}
				
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			wechatMemberService.save(wechatMember);
			
			//生成渠道二维码
			
			WechatScene wechatScene = new WechatScene();
			wechatScene.setUser(user);
			wechatScene.setType(WechatScene.SCENE_TYPE_MEMBER);		//会员推广码
			
			if(wechatScene.getSceneId()==null  || wechatScene.getSceneId() <= 0){
				Long sceneId=wechatSceneService.getSceneIdByUserId(user.getId());
				if(sceneId>100000){
					logger.error("场景值已经用完.");
				}
				wechatScene.setSceneId(sceneId);
			}
			wechatScene.setTicket(getTicket(wechatScene));
			
			wechatSceneService.save(wechatScene);
			
			logger.debug("生成会员的推广码成功...");
			
			//会员的推广码值
			wechatMember.setSceneTicket(wechatScene.getTicket());
			wechatMember.setSceneId(wechatScene.getSceneId()+"");

			if(wechatMember.getId()==null || wechatMember.getId() <= 0)	  wechatMemberService.save(wechatMember);
			// 生成推荐码  暗号
			wechatMember.setRecommendCode(""+ StringUtils.leftPad("" + wechatMember.getId(), 6, "0"));// 推荐码

			//生成会员卡号
			wechatMember.setNumber("MBR"+ StringUtils.leftPad("" + wechatMember.getId(), 10,"0")); // 会员卡号
			
			if(!advanceInterface){
				if(wechatMember.getName()==null){
					wechatMember.setName("会员"+wechatMember.getRecommendCode());
				}
			}

			wechatMemberService.save(wechatMember);
			// 把会员表推荐码字段置成会员ID 推荐码=会员ID
			// 生成会员卡
			generateMemberCard(wechatMember, request);

			//处理注册成为会员后的
			getPrize(wechatMember);
			
			
			//三级推广 关注送积分
			sendScore(wechatMember);

			/*if(user.getInterfaceFlag()){
				
					UserMessageTemplate messageTemplate= userMessageTemplateService.getUserMessageTemplateByBid(user.getId(), BusinessMessageTemplate.TO_BE_MEMBER);
					//String token = TokenUtils.getAPIToken(weChat);
					String first = "恭喜您成为了我们的会员";
					String keyword1 = wechatMember.getNumber();
					String keyword2 = com.thinkgem.jeesite.common.utils.DateUtils.formatDate(new Date(), "yyyy年MM月dd日 hh时mm分");
					String remark = "\\n尊敬的用户，您与"+keyword2+"成为"+user.getName()+"的会员。";
									//+"\\n点我完善资料，享受更多优惠！！！" ;
					String url = ""; //"http://weixin.zhaotang.net/zt/f/site/shopping/doUpdatePersonInformation?uid="+wechatMember.getUser().getId()+"&wechatId="+wechatMember.getWechatId();
					TemplateMessage tm = TemplateMessageFactory.createBecomeWechatMember(wechatMember.getWechatId(), messageTemplate.getTemplateId(), first, keyword1, keyword2, remark,url);
					TemplateMessageUtils.sendTemplateMessage(accessToken, tm);
					
			}*/
			
			return wechatMember;
		}
		return null;
	}
	
	
	/**
	 * TODO 三级推广：关注送积分
	 * @param wechatMember
	 */
	private void sendScore(WechatMember wechatMember) {
		
		RecommendConfig recommendConfig = recommendConfigService.getByUserId(wechatMember.getUser().getId());
		Date date = new Date();
		if(recommendConfig!=null && RecommendConfig.YES.equals(recommendConfig.getIsOpen()) 
			&& recommendConfig.getStartTime().getTime()<date.getTime() && date.getTime()<recommendConfig.getEndTime().getTime() ){
			if("0".equals(recommendConfig.getType())){//0：得积分兑奖品	
				//TODO ScoreUtils.addScore(wechatMember,recommendConfig.getOneselfScore(),"三级推广，关注送积分。积分兑奖品",MemberScore.TYPE_RECOMMEND_TEMP);
				
				ScoreUtils.addRecommendScore(wechatMember, recommendConfig.getOneselfScore(), "三级推广，关注送积分。积分兑奖品", MemberScore.TYPE_RECOMMEND_TEMP);
				
			}else if("1".equals(recommendConfig.getType())){//1：积分排名送奖品
				MemberScore memberScore  = new MemberScore();
				memberScore.setWechatMember(wechatMember);
				memberScore.setType(MemberScore.TYPE_RECOMMEND_TEMP);
				memberScore.setUser(wechatMember.getUser());
				memberScore.setScore(recommendConfig.getOneselfScore());			//操作的分数，有可能是负数 
				memberScore.setRemarks("三级推广，关注送积分。积分排名送奖品");
				memberScoreService.save(memberScore);
			}
			
			
			
			////////////////
			
			
			final  RecommendConfig recommendConfig1=recommendConfig;
			 final  WechatMember regMember_=wechatMember;
			  new Thread( new Runnable() {
                   @Override
                   public void run() {
                       try {
                           Thread.sleep(2000);    //延迟1秒
                         //发消息：
               		    try {
               		    	String content = recommendConfig1.getScoreMessage().replace("oneselfScore", recommendConfig1.getOneselfScore().toString());
//               		    	System.out.println(content+"//////////////////////////");
               		    	WechatInterfaceUtils.sendTextMessageToMember1(regMember_.getUser().getId(), regMember_, content);
               			} catch (Exception e) {
               				e.printStackTrace();
               			}
                       } catch (Exception e) {

                       }
                   }
               }).start();
			
			
			
		    //////////////////
		}
	}
	
	public void sendTemplateMessage(WechatMember wechatMember, Integer score, String reason){

		UserMessageTemplate messageTemplate= userMessageTemplateService.getUserMessageTemplateByBid(wechatMember.getUser().getId(), BusinessMessageTemplate.MEMBER_SCORE_CHANGE);
		if(messageTemplate!=null){
			//获得token
 			WeChat weChat =  weChatService.getWeChatByUserId(wechatMember.getUser().getId());
 			String token = TokenUtils.getAPIToken(weChat);
			
			String keyword1="";		//会员名称 
			if(StringUtils.isNotBlank(wechatMember.getName())){
				keyword1 = wechatMember.getName();
			}else if(StringUtils.isNotBlank(wechatMember.getNickname())){
				keyword1 = wechatMember.getNickname();
			}else{
				keyword1 = "匿名";
			}
			String keyword2=wechatMember.getRecommendCode();		//消费积分
			
			TemplateMessage templateMessage = TemplateMessageFactory.createWechatMember
					(wechatMember.getWechatId(),messageTemplate.getTemplateId(),"",keyword1,keyword2,reason,"","");
			TemplateMessageUtils.sendTemplateMessage(token, templateMessage);
		}
	}

	/**
	 * 生成推广码
	 *@author xiaoqian
	 * @param wechatMember
	 * @return
	 * 2015-4-7下午6:02:06
	 */
	public String sceneCodeByMemberId(WechatMember wechatMember){
		
		if(StringUtils.isEmpty(wechatMember.getSceneTicket())){
			WechatScene wechatScene = new WechatScene();
			
			wechatScene.setUser(wechatMember.getUser());
			wechatScene.setType(WechatScene.SCENE_TYPE_MEMBER);		//会员推广码
			
			if(wechatScene.getSceneId()==null){
				
				Long sceneId=wechatSceneService.getSceneIdByUserId(wechatMember.getUser());
				if(sceneId>100000){
					logger.error("场景值已经用完.");
				}
				wechatScene.setSceneId(sceneId);
			}
			wechatScene.setTicket(getTicket(wechatScene));
			wechatScene.setProcessorId("recommedProcessor");
			wechatScene.setScene(wechatMember.getNickname()+"("+wechatMember.getId()+")");
			wechatSceneService.save(wechatScene);
			
			logger.debug("生成会员的推广码成功...");
			
			//会员的推广码值
			wechatMember.setSceneTicket(wechatScene.getTicket());
			wechatMember.setSceneId(wechatScene.getSceneId()+"");
			
			wechatMemberService.save(wechatMember);
		}
		
		return "redirect:" + Global.ADMIN_PATH + "/wechat/wechatMember/?repage";
	}
	
	
	
	
	private void getPrize(WechatMember wechatMember){
		
		User user = wechatMember.getUser();
		
		
		UserDefine userDefine = WechatUtils	.getUserDefineByUserId(user.getId());
		//注册会员加积分
		if(userDefine.getRegisterScore() != null  &&  userDefine.getRegisterScore() >0){
			//wechatMember.setScore(userDefine.getRegisterScore());
			ScoreUtils.addScore(wechatMember, userDefine.getRegisterScore(),"0","注册会员送"+userDefine.getRegisterScore()/1000d+"活动积分");
		}
		
		
		boolean isRecommandMoney = false;
		//注册会员送奖金
		if(UserDefine.YES.equals(userDefine.getRecommendMoneyFlag())){		//必须是推荐的会员注册才送奖金
			isRecommandMoney = true;
		}else{
			if(	userDefine.getRegisterMoney()!= null  &&  userDefine.getRegisterMoney() >0){
				//wechatMember.setMoney(userDefine.getRecommendMoney());
				ScoreUtils.addMoney(wechatMember, userDefine.getRegisterMoney(), "注册会员送奖金");
			}
		}
		
		
		//注册送奖品
		// 是 否注册会员有礼
		if ("1".equals(userDefine.getRegLottery())) { // 注册会员有奖
			// TODO 生成注册奖品
			LotteryRecord lotteryRecord = new LotteryRecord();
			lotteryRecord.setSourceType(LotteryRecord.SURCE_TYPE_REG);
			lotteryRecord.setName(userDefine.getLotteryName());
			lotteryRecord.setStartTime(new Date());

			lotteryRecord
					.setEndTime(com.boxin.framework.base.utils.DateUtils
							.getDelayDate(userDefine
									.getLotteryValidDays()));
			lotteryRecord.setMember(wechatMember);
			lotteryRecord.setStatus(LotteryRecord.STATUS_NORMAL);
			lotteryRecord.setUser(user);

			lotteryRecordService.save(lotteryRecord);
		}
		
		
	}
	
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2015-1-22  下午4:22:11
	 * @function <p> 生成渠道二维码的 Ticket </p>
	 * @param wechatScene
	 * @return
	 */
	public String getTicket(WechatScene wechatScene){
		User user = wechatScene.getUser();
		WeChat weChat= weChatService.getWeChatByUserId(user.getId());
		String qrcodeparams="";
		JSONObject object = null;
		wechatScene.setQrcodeType("QR_LIMIT_SCENE");
		try {
			String accessToken=TokenUtils.getAPIToken(weChat);
			
//			if(wechatScene.getQrcodeType().equals("QR_SCENE")){
//				qrcodeparams=WechatInterfaceUtils.createTemporaryQrCodeParams(wechatScene.getExpireSeconds().toString(), wechatScene.getSceneId().toString());
//			}else if(wechatScene.getQrcodeType().equals("QR_LIMIT_SCENE")){
//				qrcodeparams=WechatInterfaceUtils.createForeverQrCodeParams(wechatScene.getSceneId().toString());
//			}
			qrcodeparams=WechatInterfaceUtils.createForeverQrCodeParams(wechatScene.getSceneId().toString());
			object=WechatInterfaceUtils.createQrCode(qrcodeparams, accessToken);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return object.getString("ticket");
		
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-4-3 下午2:19:47
	 * @function <p>
	 *           生成会员卡 及会员卡二维码
	 *           </p>
	 * @param member
	 * @param request
	 */
	// TODO 生成会员卡 及会员卡二维码
	private void generateMemberCard(WechatMember member,
			HttpServletRequest request) {
		QRCode qrcode = new QRCode();
		String content = member.getNumber();
		qrcode.setContent(content);
		String path = Constants.getDefaultQRCodeResourcePath();
		path = WechatUtils.getMemberCardResourceSavePath(request);
		FileUtils.createDirectory(path);
		String filePath = path + File.separator + content;

		QRCodeUtils.generateNoMarginQRCodePNG(content, filePath, 300,
				300);
		qrcode.setFileName(content + ".png");
		qrcode.setPngPath(filePath + ".png");
		qrCodeService.save(qrcode);

		member.setQrCode(qrcode);

		wechatMemberService.save(member);
		
	}

	
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-3-25  下午2:29:37
	 * @function <p> 替换 图文回复时 的URL 的动态参数 </p>
	 * @param newsReplies
	 */
	public  void replaceUrlParameters(List<NewsReply> newsReplies,User user,String openId){
		for(NewsReply reply : newsReplies){
			
			String url = reply.getUrl();
			if(StringUtils.isNotEmpty(url)){
				url = url.replaceAll("%uid%", user.getId()+"");
				url = url.replaceAll("%wid%", openId);
			}
			reply.setUrl(url);
			
		}
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-4-26  下午3:26:08
	 * @function <p> 处理替换URL </p>
	 * @param url
	 * @return
	 */
	public String replaceUrlParameters(String url,User user,String openId){
		if(StringUtils.isNotEmpty(url)){
			url = url.replaceAll("%uid%", user.getId()+"");
			url = url.replaceAll("%wid%", openId);
		}
		return url;
	}
	
	
	public void loggerMessageByClick(User user,Map<String,String> map,String keyWord){
		WechatMessage message = new WechatMessage();
		message.setUser(user);
		message.setWpId(map.get("xml.FromUserName"));
		message.setCreateTime(DataUtils.timeStampDate(map.get("xml.CreateTime")));
		message.setDay(DateUtils.getTodayString());
		message.setMonth(DateUtils.getMonthString());
		message.setYear(DateUtils.getYearString());
		message.setEventType("CLICK");
		message.setMessageType("event");
		message.setMessage(keyWord);
		wechatMessageService.save(message);
	}
	
	public void loggerMessageByView(User user,Map<String,String> map,String keyWord){
		WechatMessage message = new WechatMessage();
		message.setUser(user);
		message.setWpId(map.get("xml.FromUserName"));
		message.setCreateTime(DataUtils.timeStampDate(map.get("xml.CreateTime")));
		message.setDay(DateUtils.getTodayString());
		message.setMonth(DateUtils.getMonthString());
		message.setYear(DateUtils.getYearString());
		message.setEventType("VIEW");
		message.setMessage(keyWord);
		wechatMessageService.save(message);
	}
	
	
	public void loggerMessage(User user,Map<String,String> map,HttpServletRequest request){
		WechatMessage message = new WechatMessage();
		message.setUser(user);
		message.setWpId(map.get("xml.FromUserName"));
		message.setCreateTime(DataUtils.timeStampDate(map.get("xml.CreateTime")));
		message.setDay(DateUtils.getTodayString());
		message.setMonth(DateUtils.getMonthString());
		message.setYear(DateUtils.getYearString());
		
//		WechatMediaId wechatMediaId =new WechatMediaId();
//		wechatMediaId.setUser(user);
//		wechatMediaId.setWechatId(map.get("xml.FromUserName"));
		
		String wid		 =  request.getParameter("wid");
		
		if(EventMessage.MSG_TYPE.equals(map.get("xml.MsgType"))){//事件
				message.setMessageType("event");
				if(EventMessage.EVENT_TYPE_JOIN.equals(map.get("xml.Event"))){//订阅事件
					String msg="订阅";
					if(AssertUtils.notNullOrEmpty(map.get("xml.EventKey") )  &&	map.get("xml.EventKey").startsWith(WechatScene.SCENE_PRE_FIX) ){
						msg+="EventKey："+map.get("xml.EventKey");
						biDao.addSceneCount(user, map);//  对二维码过来的用户在bi_scene表中进行记录
					}
					if(AssertUtils.notNullOrEmpty(map.get("xml.Ticket"))){
						msg+="Ticket："+map.get("xml.Ticket");
					}
					message.setEventType("subscribe");
					message.setMessage("订阅");
					wechatMessageService.save(message);
				}else if(EventMessage.EVENT_TYPE_QUIT.equals(map.get("xml.Event"))){//退订事件
					message.setEventType("unsubscribe");
					message.setMessage("退订");
					wechatMessageService.save(message);
				}
				else if(EventMessage.EVENT_VIEW.equals(map.get("xml.Event"))){
					message.setEventType("VIEW");
					message.setMessage(map.get("xml.EventKey"));
					wechatMessageService.save(message);
				}
				else if("LOCATION".equals(map.get("xml.Event"))){
					message.setEventType("LOCATION");
					message.setMessage("Latitude："+map.get("xml.Latitude")+"-- Longitude："+map.get("xml.Longitude")+"-- Precision："+map.get("xml.Precision"));
					wechatMessageService.save(message);
				}else if("SCAN".equals(map.get("xml.Event"))){
					message.setEventType("SCAN");
					message.setMessage("EventKey："+map.get("xml.EventKey")+"-- Ticket："+map.get("xml.Ticket"));
					biDao.addSceneCount(user, map);//  对二维码过来的用户在bi_scene表中进行记录
					wechatMessageService.save(message);
					
					
					//TODO 高级业务处理
					String eventKey = map.get("xml.EventKey");
					if(eventKey.length()>8){
						eventKey =  map.get("xml.EventKey").substring(8,map.get("xml.EventKey").length() );
					}
					
					
					/////
					WechatScene wechatScene = wechatSceneService.wechatSceneBySceneId(user.getId(),Long.parseLong(eventKey));
					if(wechatScene!=null && com.thinkgem.jeesite.common.utils.StringUtils.isNotEmpty(wechatScene.getDelFlag())){
						String beanId = wechatScene.getProcessorId();
						BusinessProcessor processor =	MessageProcessorUtils.getByBeanId(beanId);
						if(processor!=null){
							processor.process();
							return;
						}
					}
					
				}
		}else if(ImageMessage.MSG_TYPE.equals(map.get("xml.MsgType"))){
			message.setMessageType("image");
			message.setMessage("图片路径："+map.get("xml.PicUrl")+"-- MediaId："+map.get("xml.MediaId"));
			wechatMessageService.save(message);
		}else if(TextMessage.MSG_TYPE.equals(map.get("xml.MsgType"))){
			message.setMessageType("text");
			message.setMessage(map.get("xml.Content"));
			wechatMessageService.save(message);
			
//			if("开挂模式".equals(SessionUtils.getLastUpContent(map.get("xml.FromUserName")))){
//				logger.debug("记录文字");
//				wechatMediaId.setMessage(map.get("xml.Content"));
//				wechatMediaIdService.save(wechatMediaId);
//			}
		}else if(LocationMessage.MSG_TYPE.equals(map.get("xml.MsgType"))){
			message.setMessageType("location");
			message.setMessage("Location_X："+map.get("xml.Location_X")+"--Location_Y："+map.get("xml.Location_Y")+"--Scale："+map.get("xml.Scale")+"--Label："+map.get("xml.Label"));
			wechatMessageService.save(message);
		}else if(VoiceMessage.MSG_TYPE.equals(map.get("xml.MsgType"))){
			if(user.getInterfaceFlag()){
				message.setMessage("MediaId："+map.get("xml.MediaId")+"--Recognition："+map.get("xml.Recognition"));
			}
			message.setMessage("MediaId："+map.get("xml.MediaId"));
			message.setMessageType("voice");
			wechatMessageService.save(message);
//			if("开挂模式".equals(SessionUtils.getLastUpContent(map.get("xml.FromUserName")))){
//				logger.debug("记录语音");
//				wechatMediaId.setMedia_id(map.get("xml.MediaId"));
//				wechatMediaIdService.save(wechatMediaId);
//			}
		}else if("video".equals(map.get("xml.MsgType"))){
			message.setMessage("MediaId："+map.get("xml.MediaId")+"--ThumbMediaId："+map.get("xml.ThumbMediaId"));
			message.setMessageType("video");
			wechatMessageService.save(message);
		}else if("link".equals(map.get("xml.MsgType"))){
			message.setMessage("Title："+map.get("xml.Title")+"--Description："+map.get("xml.Description")+"--Url："+map.get("xml.Url"));
			message.setMessageType("link");
			wechatMessageService.save(message);
		}
			
	}
	
	/**
	 * 处理替换文本回复消息中的url
	 * @param user
	 * @param map
	 * @param keyWord
	 */
	public String replaceContentParameters(String content,User user,String openId){
		if(StringUtils.isNotEmpty(content)){
			content = content.replaceAll("%uid%", user.getId()+"");
			content = content.replaceAll("%wid%", openId);
		}
		return content;
	}
	
}
